#!/bin/sh

set -e

case "$1" in
	encrypt)
		cd /var/lib/secrets/ || exit
		tar -cf secrets.tar ./*
		cd /usr/share/secrets/ || exit
		mv /var/lib/secrets/secrets.tar .
		age -e -r age122g2ufaa494vj9yqcqh0l6390l38j0j4v80ganlx9eg7v07a3eps3te4ac <secrets.tar >secrets.tar.age
		shred -zu secrets.tar
		;;
	decrypt)
		cd /usr/share/secrets/ || exit
		printf 'key: '
		read -r key
		echo "$key" >/tmp/secrets.key
		age -d -i /tmp/secrets.key <secrets.tar.age >secrets.tar
		cd /var/lib/secrets/ || exit
		tar -x --overwrite -f /usr/share/secrets/secrets.tar
		chmod g+rX /var/lib/secrets/ -R
		find . -type f | while IFS= read -r secret
		do
			rm -f "/$secret"
			ln -sf "/var/lib/secrets/$secret" "/$secret"
		done
		shred -zu /usr/share/secrets/secrets.tar
		shred -zu /tmp/secrets.key
		;;
	*)
		echo 'secrets (encrypt|decrypt)'
		;;
esac
